#region Using

using System;
using System.IO;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using CoyoEden;
using CoyoEden.Models;

#endregion

public partial class admin_Pages_configuration : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            BindThemes();
            BindCultures();
            BindSettings();
        }

        Page.MaintainScrollPositionOnPostBack = true;
        Page.Title = Resources.labels.settings;

        btnSave.Click += new EventHandler(btnSave_Click);
        btnSaveTop.Click += new EventHandler(btnSave_Click);
        btnTestSmtp.Click += new EventHandler(btnTestSmtp_Click);

        btnSaveTop.Text = Resources.labels.saveSettings;
        btnSave.Text = btnSaveTop.Text;
    }

    private void btnTestSmtp_Click(object sender, EventArgs e) {
        try {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(txtEmail.Text, txtName.Text);
            mail.To.Add(mail.From);
            mail.Subject = "Test mail from " + txtName.Text;
            mail.Body = "Success";
            SmtpClient smtp = new SmtpClient(txtSmtpServer.Text);
            smtp.Credentials = new System.Net.NetworkCredential(txtSmtpUsername.Text, txtSmtpPassword.Text);
            smtp.EnableSsl = cbEnableSsl.Checked;
            smtp.Port = int.Parse(txtSmtpServerPort.Text, CultureInfo.InvariantCulture);
            smtp.Send(mail);
            lbSmtpStatus.Text = "Test successfull";
            lbSmtpStatus.Style.Add(HtmlTextWriterStyle.Color, "green");
        } catch {
            lbSmtpStatus.Text = "Could not connect";
            lbSmtpStatus.Style.Add(HtmlTextWriterStyle.Color, "red");
        }
    }

    private void btnSave_Click(object sender, EventArgs e) {
        //-----------------------------------------------------------------------
        // Set Basic settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.Name = txtName.Text;
        PortalSettings.Instance.Description = txtDescription.Text;
        PortalSettings.Instance.PostsPerPage = int.Parse(txtPostsPerPage.Text);
        PortalSettings.Instance.Theme = ddlTheme.SelectedValue;
        PortalSettings.Instance.MobileTheme = ddlMobileTheme.SelectedValue;
				PortalSettings.Instance.UseBlogNameInPageTitles = cbUseBlogNameInPageTitles.Checked;
        PortalSettings.Instance.EnableRelatedPosts = cbShowRelatedPosts.Checked;
        PortalSettings.Instance.EnableRating = cbEnableRating.Checked;
        PortalSettings.Instance.ShowDescriptionInPostList = cbShowDescriptionInPostList.Checked;
        PortalSettings.Instance.TimeStampPostLinks = cbTimeStampPostLinks.Checked;
				PortalSettings.Instance.ShowPostNavigation = cbShowPostNavigation.Checked;
        PortalSettings.Instance.Culture = ddlCulture.SelectedValue;
        PortalSettings.Instance.Timezone = double.Parse(txtTimeZone.Text, CultureInfo.InvariantCulture);

        //-----------------------------------------------------------------------
        // Set Email settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.Email = txtEmail.Text;
        PortalSettings.Instance.SmtpServer = txtSmtpServer.Text;
        PortalSettings.Instance.SmtpServerPort = int.Parse(txtSmtpServerPort.Text);
        PortalSettings.Instance.SmtpUserName = txtSmtpUsername.Text;
        PortalSettings.Instance.SmtpPassword = txtSmtpPassword.Text;
        PortalSettings.Instance.SendMailOnComment = cbComments.Checked;
        PortalSettings.Instance.EnableSsl = cbEnableSsl.Checked;
        PortalSettings.Instance.EmailSubjectPrefix = txtEmailSubjectPrefix.Text;

        PortalSettings.Instance.EnableEnclosures = cbEnableEnclosures.Checked;

        //-----------------------------------------------------------------------
        // Set Comments settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.IsCommentsEnabled = cbEnableComments.Checked;
        PortalSettings.Instance.EnableCountryInComments = cbEnableCountryInComments.Checked;
        PortalSettings.Instance.IsCoCommentEnabled = cbEnableCoComment.Checked;
        PortalSettings.Instance.ShowLivePreview = cbShowLivePreview.Checked;
        PortalSettings.Instance.DaysCommentsAreEnabled = int.Parse(ddlCloseComments.SelectedValue);
        PortalSettings.Instance.EnableCommentsModeration = cbEnableCommentsModeration.Checked;
        PortalSettings.Instance.Avatar = rblAvatar.SelectedValue;

        //-----------------------------------------------------------------------
        // Set Advanced settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.EnableHttpCompression = cbEnableCompression.Checked;
        PortalSettings.Instance.RemoveWhitespaceInStyleSheets = cbRemoveWhitespaceInStyleSheets.Checked;
				PortalSettings.Instance.CompressWebResource = cbCompressWebResource.Checked;
        PortalSettings.Instance.EnableOpenSearch = cbEnableOpenSearch.Checked;
				PortalSettings.Instance.RequireSSLMetaWeblogAPI = cbRequireSslForMetaWeblogApi.Checked;
        PortalSettings.Instance.HandleWwwSubdomain = rblWwwSubdomain.SelectedItem.Value;
				PortalSettings.Instance.EnableTrackBackSend = cbEnableTrackBackSend.Checked;
				PortalSettings.Instance.EnableTrackBackReceive = cbEnableTrackBackReceive.Checked;
				PortalSettings.Instance.EnablePingBackSend = cbEnablePingBackSend.Checked;
				PortalSettings.Instance.EnablePingBackReceive = cbEnablePingBackReceive.Checked;

        //-----------------------------------------------------------------------
        // Set Syndication settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.SyndicationFormat = ddlSyndicationFormat.SelectedValue;
        PortalSettings.Instance.PostsPerFeed = int.Parse(txtPostsPerFeed.Text, CultureInfo.InvariantCulture);
        PortalSettings.Instance.AuthorName = txtDublinCoreCreator.Text;
        PortalSettings.Instance.Language = txtDublinCoreLanguage.Text;

        float latitude;
        if (Single.TryParse(txtGeocodingLatitude.Text, out latitude)) {
            PortalSettings.Instance.GeocodingLatitude = latitude;
        } else {
            PortalSettings.Instance.GeocodingLatitude = Single.MinValue;
        }
        float longitude;
        if (Single.TryParse(txtGeocodingLongitude.Text, out longitude)) {
            PortalSettings.Instance.GeocodingLongitude = longitude;
        } else {
            PortalSettings.Instance.GeocodingLongitude = Single.MinValue;
        }

        PortalSettings.Instance.Endorsement = txtBlogChannelBLink.Text;

        if (txtAlternateFeedUrl.Text.Trim().Length > 0 && !txtAlternateFeedUrl.Text.Contains("://"))
            txtAlternateFeedUrl.Text = "http://" + txtAlternateFeedUrl.Text;

        PortalSettings.Instance.AlternateFeedUrl = txtAlternateFeedUrl.Text;

        //-----------------------------------------------------------------------
        // HTML header section
        //-----------------------------------------------------------------------
        PortalSettings.Instance.HtmlHeader = txtHtmlHeader.Text;

        //-----------------------------------------------------------------------
        // Visitor tracking settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.TrackingScript = txtTrackingScript.Text;

        //-----------------------------------------------------------------------
        //  Persist settings
        //-----------------------------------------------------------------------
        PortalSettings.Instance.Save();
        Response.Redirect(Request.RawUrl, true);
    }

    private void BindSettings() {
        //-----------------------------------------------------------------------
        // Bind Basic settings
        //-----------------------------------------------------------------------
        txtName.Text = PortalSettings.Instance.Name;
        txtDescription.Text = PortalSettings.Instance.Description;
        txtPostsPerPage.Text = PortalSettings.Instance.PostsPerPage.ToString();
        cbShowRelatedPosts.Checked = PortalSettings.Instance.EnableRelatedPosts;
        ddlTheme.SelectedValue = PortalSettings.Instance.Theme;
        ddlMobileTheme.SelectedValue = PortalSettings.Instance.MobileTheme;
				cbUseBlogNameInPageTitles.Checked = PortalSettings.Instance.UseBlogNameInPageTitles;
        cbEnableRating.Checked = PortalSettings.Instance.EnableRating;
        cbShowDescriptionInPostList.Checked = PortalSettings.Instance.ShowDescriptionInPostList;
        cbTimeStampPostLinks.Checked = PortalSettings.Instance.TimeStampPostLinks;
        ddlCulture.SelectedValue = PortalSettings.Instance.Culture;
        txtTimeZone.Text = PortalSettings.Instance.Timezone.ToString();

        //-----------------------------------------------------------------------
        // Bind Comments settings
        //-----------------------------------------------------------------------
        cbEnableComments.Checked = PortalSettings.Instance.IsCommentsEnabled;
        cbEnableCountryInComments.Checked = PortalSettings.Instance.EnableCountryInComments;
        cbEnableCoComment.Checked = PortalSettings.Instance.IsCoCommentEnabled;
        cbShowLivePreview.Checked = PortalSettings.Instance.ShowLivePreview;
				cbShowPostNavigation.Checked = PortalSettings.Instance.ShowPostNavigation;
        ddlCloseComments.SelectedValue = PortalSettings.Instance.DaysCommentsAreEnabled.ToString();
        cbEnableCommentsModeration.Checked = PortalSettings.Instance.EnableCommentsModeration;
        rblAvatar.SelectedValue = PortalSettings.Instance.Avatar;

        //-----------------------------------------------------------------------
        // Bind Email settings
        //-----------------------------------------------------------------------
        txtEmail.Text = PortalSettings.Instance.Email;
        txtSmtpServer.Text = PortalSettings.Instance.SmtpServer;
        txtSmtpServerPort.Text = PortalSettings.Instance.SmtpServerPort.ToString();
        txtSmtpUsername.Text = PortalSettings.Instance.SmtpUserName;
        txtSmtpPassword.Text = PortalSettings.Instance.SmtpPassword;
        cbComments.Checked = PortalSettings.Instance.SendMailOnComment;
        cbEnableSsl.Checked = PortalSettings.Instance.EnableSsl;
        txtEmailSubjectPrefix.Text = PortalSettings.Instance.EmailSubjectPrefix;

        cbEnableEnclosures.Checked = PortalSettings.Instance.EnableEnclosures;

        //-----------------------------------------------------------------------
        // Bind Advanced settings
        //-----------------------------------------------------------------------
        cbEnableCompression.Checked = PortalSettings.Instance.EnableHttpCompression;
        cbRemoveWhitespaceInStyleSheets.Checked = PortalSettings.Instance.RemoveWhitespaceInStyleSheets;
				cbCompressWebResource.Checked = PortalSettings.Instance.CompressWebResource;
        cbEnableOpenSearch.Checked = PortalSettings.Instance.EnableOpenSearch;
				cbRequireSslForMetaWeblogApi.Checked = PortalSettings.Instance.RequireSSLMetaWeblogAPI;
        rblWwwSubdomain.SelectedValue = PortalSettings.Instance.HandleWwwSubdomain;
				cbEnablePingBackSend.Checked = PortalSettings.Instance.EnablePingBackSend;
				cbEnablePingBackReceive.Checked = PortalSettings.Instance.EnablePingBackReceive;
				cbEnableTrackBackSend.Checked = PortalSettings.Instance.EnableTrackBackSend;
				cbEnableTrackBackReceive.Checked = PortalSettings.Instance.EnableTrackBackReceive;

        //-----------------------------------------------------------------------
        // Bind Syndication settings
        //-----------------------------------------------------------------------
        ddlSyndicationFormat.SelectedValue = PortalSettings.Instance.SyndicationFormat;
        txtPostsPerFeed.Text = PortalSettings.Instance.PostsPerFeed.ToString();
        txtDublinCoreCreator.Text = PortalSettings.Instance.AuthorName;
        txtDublinCoreLanguage.Text = PortalSettings.Instance.Language;

        txtGeocodingLatitude.Text = PortalSettings.Instance.GeocodingLatitude != Single.MinValue ? PortalSettings.Instance.GeocodingLatitude.ToString() : String.Empty;
        txtGeocodingLongitude.Text = PortalSettings.Instance.GeocodingLongitude != Single.MinValue ? PortalSettings.Instance.GeocodingLongitude.ToString() : String.Empty;

        txtBlogChannelBLink.Text = PortalSettings.Instance.Endorsement;
        txtAlternateFeedUrl.Text = PortalSettings.Instance.AlternateFeedUrl;

        //-----------------------------------------------------------------------
        // HTML header section
        //-----------------------------------------------------------------------
        txtHtmlHeader.Text = PortalSettings.Instance.HtmlHeader;

        //-----------------------------------------------------------------------
        // Visitor tracking settings
        //-----------------------------------------------------------------------
        txtTrackingScript.Text = PortalSettings.Instance.TrackingScript;
    }

    private void BindThemes() {
        string path = Server.MapPath(Utils.RelativeWebRoot + "themes/");
        foreach (string dic in Directory.GetDirectories(path)) {
            int index = dic.LastIndexOf(Path.DirectorySeparatorChar) + 1;
            ddlTheme.Items.Add(dic.Substring(index));
            ddlMobileTheme.Items.Add(dic.Substring(index));
        }
    }

    private void BindCultures() {
        if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "PrecompiledApp.config"))) {

            string precompiledDir = HttpRuntime.BinDirectory;
            string[] translations = Directory.GetFiles(precompiledDir, "App_GlobalResources.resources.dll", SearchOption.AllDirectories);
            foreach (string translation in translations) {
                string resourceDir = Path.GetDirectoryName(translation).Remove(0, precompiledDir.Length);
                if (!String.IsNullOrEmpty(resourceDir)) {

                    System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag(resourceDir);
                    ddlCulture.Items.Add(new ListItem(info.NativeName, resourceDir));
                }
            }
        } else {

            string path = Server.MapPath(Utils.RelativeWebRoot + "App_GlobalResources/");
            foreach (string file in Directory.GetFiles(path, "labels.*.resx")) {

                int index = file.LastIndexOf(Path.DirectorySeparatorChar) + 1;
                string filename = file.Substring(index);
                filename = filename.Replace("labels.", string.Empty).Replace(".resx", string.Empty);
                System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag(filename);
                ddlCulture.Items.Add(new ListItem(info.NativeName, filename));

            }
        }
    }

}